//
//  CStudentSave.m
//  Hello Box2d
//
//  Created by niko on 10-9-27.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CStudentSave.h"


@implementation CStudentSave

@synthesize m_nStudentID;
@synthesize m_strStudentName;

#pragma mark NSCoding
-(void)encodeWithCoder:(NSCoder *)aCoder
{
	[aCoder encodeInt:m_nStudentID forKey: @"ID"];
	[aCoder encodeObject:m_strStudentName forKey: @"Name"];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
	if ( (self = [super init]) ) 
	{
		m_nStudentID = [aDecoder decodeIntForKey:@"ID"];
		m_strStudentName = [aDecoder decodeObjectForKey:@"Name"];
	}
	return self;
}

#pragma mark NSCopying
-(id)copyWithZone:(NSZone *)zone
{
	CStudentSave *copy = [[[self class] allocWithZone: zone] init];
	copy.m_nStudentID = self.m_nStudentID;
	copy.m_strStudentName = [self.m_strStudentName copy];
	
	return copy;
}

-(void) Save
{
	//写入二进制文件
	CStudentSave *sStudent = [[[CStudentSave alloc] init] autorelease];
	sStudent.m_nStudentID = 1001;
	NSString *temp_1 = @"DSBZHaoGuoTao";
	sStudent.m_strStudentName = temp_1;
	NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
	NSString *documentDir = [pathArray objectAtIndex:0];
	
	NSString *path = [documentDir stringByAppendingPathComponent:@"test.dat"];//@"/Users/niko/Desktop/test.dat";
	NSMutableData *writer = [[NSMutableData alloc] init];
	NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:writer];
	[archiver encodeObject:sStudent forKey:@"SBZHaoGuoTao"];
	[archiver finishEncoding];
	BOOL bSuccess = [writer writeToFile:path atomically:YES];
	NSLog(@"Success:%i", bSuccess);
	[archiver release];
	[writer release];
	
	//读出二进制文件
	NSData *reader = [NSData dataWithContentsOfFile:path];
	NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:reader];
	CStudentSave *sStudent2 = [unarchiver decodeObjectForKey: @"SBZHaoGuoTao"];
	NSLog(@"----- Name:%@ ID:%i", sStudent2.m_strStudentName, sStudent2.m_nStudentID);
	[unarchiver finishDecoding];
	[unarchiver release];
	[sStudent2 release];
	[reader release];
	
}
@end


